/**   
* @Title: DesignPatternXMLParser.java
* @Package cn.edu.sjtu.se.dslab.component.dp.parse
* @Description: 定义解析design pattern配置文件的类
* @author Thinker
* @date 2013-7-26 下午8:39:31
* @version V1.0
*/ 
package cn.edu.sjtu.se.dslab.component.dp.parse;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.edu.sjtu.se.dslab.util.FileUtil;

/** 
 * @ClassName: DesignPatternXMLParser
 * @Description: 解析DesignPattern
 * @author longshaohang
 * @date 2013-7-26 下午8:39:31
 * 
 */
public class DesignPatternXMLParser {
	private Document document;
	private DesignPatternBean dpBean;

	public DesignPatternXMLParser(String path) {
		path = FileUtil.getRootPath() + path;
		SAXReader reader = new SAXReader();
		try {
			document = reader.read(new File(path));
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	public DesignPatternBean parse(){
		dpBean = new DesignPatternBean();
		if(document == null) return null;
		readDesignPattern();
		return dpBean;
	}
	
	private void readDesignPattern(){
		Element rootElement = document.getRootElement();
		dpBean.setName( rootElement.attributeValue( DesignPatternBean.NAME_ATTR ) );
		dpBean.setLabelText( rootElement.elementText( DesignPatternBean.LABEL));
		readProperties(rootElement.element(DesignPatternBean.PROPERTIES));
	}

	private void readProperties(Element properties){
		@SuppressWarnings("unchecked")
		List<Element> elements = properties.elements();
		for(Element element: elements){
			Property p = readProperty(element);
			dpBean.getProperties().add(p);
		}
	}

	private Property readProperty(Element element){
		Property p = new Property();
		p.setName( element.attributeValue( Property.NAME_ATTR));
		p.setLabel(element.elementText( Property.PROPERTY_LABEL));
		p.setType(element.elementText(Property.VALUE_TYPE));
		return p;
	}
}
